package com.itheima02.thread;

public class Demo6_Thread {
    public static void main(String[] args) {
        Printer p = new Printer();
        //线程1
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        p.print1();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        //线程2
        new Thread(){
            @Override
            public void run() {
                while (true) {
                    try {
                        p.print2();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}

class Printer {
    int flag = 1;

    public void print1() throws InterruptedException {
        synchronized (Printer.class) {
            if (flag != 1) {
                /*
                    wait方法：如果使用的是空参数(点死穴)，就必须由一个notify方法对其进行唤醒
                 */
                Printer.class.wait();
            }
            System.out.println("黑马程序员");
            flag = 2;
            //notify唤醒线程（解穴）
            Printer.class.notify();
        }
    }

    public void print2() throws InterruptedException {
        synchronized (Printer.class) {
            if (flag != 2) {
                Printer.class.wait();
            }
            System.out.println("传智播客");
            flag = 1;
            Printer.class.notify();
        }
    }
}